const chokidar = require('chokidar');
var fs = require('fs');
var path = require('path');
const crypto = require('crypto');
const { Sequelize, QueryTypes } = require('sequelize');
const sequelizeInner = new Sequelize({
    dialect: "sqlite",
    storage: path.join(__dirname, "../../db/test.db"),
});

// const dir = 'F:\\mangage-svg-app\\design';
const dir = '../../svg/design/';
console.log('dir', path.join(__dirname, dir));
const absoluteDir = path.join(__dirname, dir);

const watcher = chokidar.watch(absoluteDir, {
    // eslint-disable-next-line no-useless-escape
    ignored: /(^|[\/\\])\../, // ignore dotfiles
    persistent: true
});

// Something to use when events are received.
const log = console.log.bind(console);
// Add event listeners.
watcher
    .on('add', path => onAdd(path))
    .on('change', path => onChange(path))
    .on('unlink', path => onDelete(path));

// 空文件夹操作不会触发监听；若文件夹里有文件，会触发监听
// 文件添加：重命名场景下，新文件名会走到这里（1）
async function onAdd(path) {
    log(`File ${path} has been added`)
    if (path.indexOf('.psd') > -1 || path.indexOf('.ai') > -1) {
        return
    }
    const fileInfo = parseFileInfo(path)
    const res = await recordsExist(fileInfo.folder, fileInfo.fileName)
    log(res)
    if (res.length > 0 && res[0].num === 0) {
        // 是新增的图片，需要插入
        insertOneFile(fileInfo.folder, fileInfo.fileName, path, fileInfo.relativePath, fileInfo.md5);
    }
}

// 文件改变：
function onChange(path) {
    log(`File ${path} has been changed`)
    if (path.indexOf('.psd') > -1 || path.indexOf('.ai') > -1) {
        return
    }
    const md5Current = crypto.createHash('md5').update(path).digest('hex');
    // log(md5Current);
}

// 文件删除：重命名的场景下，源文件名会走到这里（2）
function onDelete(path) {
    log(`File ${path} has been deleted`)
    if (path.indexOf('.psd') > -1 || path.indexOf('.ai') > -1) {
        return
    }
    const fileInfo = parseFileInfo(path)
    deleteOneRecord(fileInfo.folder, fileInfo.fileName)
}

function parseFileInfo(path) {
    const md5Current = crypto.createHash('md5').update(path).digest('hex');
    // log(md5Current);
    const index1 = path.indexOf(absoluteDir)
    if (index1 === -1) {
        return
    }
    const relativePath = path.substr(index1 + absoluteDir.length)
    const index2 = relativePath.indexOf('\\')
    if (index2 === -1) {
        return
    }
    const folder = relativePath.substr(0, index2)
    const file = relativePath.substr(index2 + 1)
    const index3 = file.indexOf('.png')
    if (index3 === -1) {
        return
    }
    const name = file.substr(0, index3)
    return {
        md5: md5Current,
        relativePath: relativePath,
        folder: folder,
        fileName: name
    }
}

function recordsExist(folder, fileName) {
    let body;
    try {
        body = sequelizeInner.query(
            `SELECT count(1) as num from design_records where folder = '${folder}' and file_name = '${fileName}' and is_delete = 0;`,
            {
                timestamps: false,
                plain: false,
                raw: false,
                type: QueryTypes.SELECT,
            }
        );
    } catch (error) {
        body = '';
    }
    return body;
}

function insertOneFile(folder, fileName, fullPath, relativePath, md5) {
    let body;
    // fullPath = fullPath.replace(/\\/g, '\\\\')
    // relativePath = relativePath.replace(/\\/g, '\\\\')
    try {
        body = sequelizeInner.query(
            `INSERT INTO design_records(id, folder, file_name, full_path, relative_path, md5, view_count, download_count, is_delete)
                    values(NULL, '${folder}', '${fileName}', '${fullPath}', '${relativePath}', '${md5}', 0, 0, 0)`,
            {
                timestamps: false,
                plain: false,
                raw: false,
                type: QueryTypes.INSERT,
            }
        );
    }catch (error) {
        body = '';
    }
    return body;
}

function deleteOneRecord(folder, fileName) {
    let body;
    try {
        body = sequelizeInner.query(
            `UPDATE design_records set is_delete = 1 where folder = '${folder}' and file_name = '${fileName}';`,
            {
                timestamps: false,
                plain: false,
                raw: false,
                type: QueryTypes.UPDATE,
            }
        );
    } catch (error) {
        body = '';
    }
    return body;
}
